package com.yunshipei.ui.activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.base.EnterBaseSubscriber;
import com.yunshipei.enterplorer.R;
import com.yunshipei.manager.YspPreferences;
import com.yunshipei.model.IBeaconClass;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.dialog.WaitDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * Created by cike on 16/4/13.
 */

public class SignInActivity extends BaseActivity {
    private final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_FINE_LOCATION = 0;
    private ArrayList<IBeaconClass.iBeacon> mLeDevices1 = new ArrayList<>();
    private SharedPreferences mySharedPreferences = YspPreferences.getInstance().getSharedPreferences();
    private String beaconUuid = "", major = "", minor = "";
    private YspTitleBar titleBar = null;
    /**
     * 搜索BLE终端
     */
    private BluetoothAdapter mBluetoothAdapter = null;
    /**
     * 读取BLE终端
     */
    private boolean mScanning;
    private Handler mhandler;
    /**
     * 刷新频率
     */
    private static final long SCAN_PERIOD = 5000;
    private WaitDialog progressDialog = null;
    private TextView majorText, minorText, uuidText, nameText;
    private Button okBut;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth_layout);
        initView();
        initData();
        progressDialog = DialogHelper.getWaitDialog(this, "搜索蓝牙设备中...");
        progressDialog.show();
    }

    private void initView() {
        uuidText = (TextView) findViewById(R.id.text);
        majorText = (TextView) findViewById(R.id.major);
        minorText = (TextView) findViewById(R.id.minor);
        nameText = (TextView) findViewById(R.id.name);
        okBut = (Button) findViewById(R.id.ok);
        titleBar = (YspTitleBar) findViewById(R.id.title_bar);
    }

    private void initData() {
        titleBar.setTitle("签  到");
        mhandler = new Handler();
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("此设备不支持Beacon");
            finish();
        }
        final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {
            showToast("此设备不支持蓝牙");
            finish();
            return;
        }
        mBluetoothAdapter.enable();     //开启蓝牙
        okBut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn(beaconUuid, major, minor);
            }
        });
    }

    /**
     * 添加设备
     *
     * @param device
     */
    private void addDevice(IBeaconClass.iBeacon device) {
        if (device == null) {
            Log.e(TAG, "device is null");
            return;
        }
        if (!mLeDevices1.contains(device)) {
            mLeDevices1.add(device);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mayRequestLocation(this);
        // Init
        scanLeDevice(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    private void showToast(String str) {
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            //扫描结束之后设置一个定时扫描
            mhandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mleScanCallback);
                    progressDialog.cancel();
                    if (!mLeDevices1.isEmpty()) {
                        IBeaconClass.iBeacon maxIBeacon = mLeDevices1.get(mLeDevices1.size() - 1);
                        beaconUuid = maxIBeacon.proximityUuid;
                        major = String.valueOf(maxIBeacon.major);
                        minor = Integer.toHexString(maxIBeacon.minor);
                        uuidText.setText(String.format("UUID:  %s", beaconUuid));
                        majorText.setText(String.format("major:  0x%s", major).toUpperCase());
                        minorText.setText(String.format("minor:  0x%s", minor).toUpperCase());
                        nameText.setText(String.format("签到人:  %s", mySharedPreferences.getString("name", "")).toUpperCase());
                    }
                }
            }, SCAN_PERIOD);
            mScanning = true;
            mBluetoothAdapter.startLeScan(mleScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mleScanCallback);
        }
    }

    private BluetoothAdapter.LeScanCallback mleScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
            IBeaconClass.iBeacon iBeacon = IBeaconClass.fromScanData(device, rssi, scanRecord);
            addDevice(iBeacon);
            Collections.sort(mLeDevices1, new Comparator<IBeaconClass.iBeacon>() {
                @Override
                public int compare(IBeaconClass.iBeacon lhs, IBeaconClass.iBeacon rhs) {
                    return lhs.rssi - rhs.rssi;
                }
            });
        }
    };


    private void mayRequestLocation(Context context) {
        if (Build.VERSION.SDK_INT >= 23) {
            Log.e("mayRequestLocation", "系统版本大于23请求运行时权限");
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION))
                    Toast.makeText(context, "需要搜索蓝牙设备", Toast.LENGTH_LONG).show();
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_FINE_LOCATION);
                return;
            } else {

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        Log.e("requestPermissionResult", String.valueOf(requestCode));
        switch (requestCode) {
            case REQUEST_FINE_LOCATION:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // The requested permission is granted.
                    if (mScanning == false) {
                        scanLeDevice(true);
                    }
                } else {
                    // The user disallowed the requested permission.
                }
                break;
        }
    }

    private void signIn(String beaconUuid, String major, String minor) {
        String companyId = "";
        String name = "";
        if (mySharedPreferences != null) {
            companyId = mySharedPreferences.getString("company_id", "");
            name = mySharedPreferences.getString("name", "");
        }
        HttpMethods.getInstance().checkIn(beaconUuid, major, minor, companyId, name, new EnterBaseSubscriber() {
            @Override
            public void onSuccess(JSONObject data) {
                showToast("签到成功");
                okBut.setEnabled(false);
            }

            @Override
            public void onFailure(String errorMessage) {
                showToast("签到失败");
            }
        });
    }
}

